package cqrtplm.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.model.constant.ProcessConstant;
import com.ty.basic.session.RequestContext;
import cqrtplm.service.SapIntegrityIntefaceService;
import cqrtplm.service.SapIntegrityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.runtime.Execution;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : pieStar
 * @create 2025/7/22 21:54
 */
@Slf4j
@CustomListener(category = "润通", description = "成品BOM和编码主数据下发SAP")
public class RTBOMAndMaterialsToSAPListener implements ExecutionListener {
    @Override
    public void notify(DelegateExecution delegateExecution) {
        long start = System.currentTimeMillis();
        String workFlowContainerId = delegateExecution.getProcessInstanceBusinessKey();
        log.info("----------润通----成品BOM和编码主数据下发SAP------开始------workFlowContainerId:{}----->>>",workFlowContainerId);
        if (StringUtils.isBlank(workFlowContainerId)) {
            workFlowContainerId = delegateExecution.getVariable(ProcessConstant.WORK_FLOW_CONTAINER_ID).toString();
        }
        String finalWorkFlowContainerId = workFlowContainerId;
        Map<String, Object> requestContext = RequestContext.currentContext();
//        SapIntegrityService
//        SapIntegrityIntefaceService
        SapIntegrityIntefaceService sapIntegrityService = SpringUtil.getBean(SapIntegrityIntefaceService.class);
        String processInstanceId = delegateExecution.getProcessInstanceId();
        CompletableFuture.runAsync(() -> {
            boolean flag = false;
            String code = "";
            RequestContext.attachContext(requestContext);
            try {
                sapIntegrityService.bomAndMaterialsToSAP(new BigInteger(finalWorkFlowContainerId),"all");
                flag = true;
            } catch (Exception e) {
//                RequestLogDTO dto = new RequestLogDTO()
//                        .setExternalSystems(ExternalSystemsEnum.SAP)
//                        .setRequestType(RequestLogEnum.RequestType.DATABASE)
//                        .setUrl("")
//                        .setResend(YesOrNoEnum.N)
//                        .setName("BOM状态检查")
//                        .setInput("")
//                        .setWorkflowNumber(code);
//                requestLogHelper.failed(dto, e.getMessage());
                log.info("BOM下发可回退至状态室处理节点：", e);
            } finally {
                RuntimeService runtimeService = SpringUtil.getBean(RuntimeService.class);
                Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).
                        parentId(processInstanceId).singleResult();
                runtimeService.setVariable(execution.getId(), "SJXF", flag);
                log.info("更新流程变量 SJXF -> {}", flag);
                runtimeService.messageEventReceived("SJXF_MSG", execution.getId());
                log.info("润通二开定制监听，消息发送 SJXF_MSG");
                log.info("----------润通----BOM状态检查监听结束,耗时：{}---->>>", System.currentTimeMillis() - start);
            }
        });
    }
}
